package com.stockz.ui.swing.charting.display.indicator;

import java.awt.Graphics2D;
import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.stockz.core.model.Bar;
import com.stockz.core.util.ListUtil;
import com.stockz.ui.swing.charting.painter.indicator.LineIndicatorPainter;
import com.stockz.ui.swing.charting.util.MathUtil;
import com.stockz.ui.swing.charting.util.UIChartingConstant.OVERLAY;

@Component
@Scope("prototype")
public class Stochastics extends AbstractDisplayableIndicatorConfiguration {
	public static class Configuration{
		private int span = 20;
		
		public int getSpan() {
			return span;
		}
		public void setSpan(int span) {
			this.span = span;
		}
	}
	
	public static double value(double[] barValues, int span, int offset){
		double max = MathUtil.max(barValues, offset, offset+span);
		double min = MathUtil.min(barValues,offset, offset+span);
		if(max == min){
			return 0;
		}else{
			return ((barValues[offset]-min)*100)/(max-min);
		}
		
	}
	
	public static double value(double[] barValues, int span){
		double max = MathUtil.max(barValues, 0, span);
		double min = MathUtil.min(barValues, 0, span);
		if(max == min){
			return 0;
		}else{
			return ((barValues[0]-min)*100)/(max-min);
		}
	}
	
	public static double[] values(double[] barValues, int span){
		if(barValues != null && span > 0 && barValues.length > span){
			double[] values = new double[barValues.length];
			for(int i = barValues.length - 1 - span; i >= 0; i--){
				values[i] = value(barValues,span,i);
			}
			return values;
		}
		return new double[0];
	}
	
	private Configuration configuration = new Configuration();

	@Override
	public void paint(Graphics2D g) {
		LineIndicatorPainter.paint(g, this);
	}
	
	@Override
	public Object getConfiguration() {
		return configuration;
	}
	
	@Override
	public OVERLAY getOverlay() {
		return OVERLAY.INDEPENDENT;
	}
	
	@Override
	public String getDescription() {
		return getShortName()+","+configuration.getSpan()
		+","+getBarValueType();
	}

	@Override
	public boolean isOverlappable() {
		return true;
	}

	@Override
	public String getFullName() {
		return "Stochastics";
	}

	@Override
	public String getShortName() {
		return "STO";
	}

	@Override
	public void refreshValues() {
		List<Bar> barList = getStockChartPanel().getStockChartPanelState().getBarList();
		if(barList != null && barList.size() > configuration.getSpan()){
			double[] barValues = ListUtil.convert(barList, getBarValueType());
			setValues(values(barValues, configuration.getSpan()));
		}
	}
}
